import React, { useState, useRef } from "react";
import { Progress } from "antd";
import {
  CaretRightOutlined,
  CompressOutlined,
  ExpandOutlined,
  PauseOutlined,
} from "@ant-design/icons";
import styles from "./index.less";

var timer: NodeJS.Timer | undefined;

const VideoPlayer = ({
  urls,
  width,
}: {
  urls: string[];
  width: number | string;
}) => {
  const [controlsVisible, setControlsVisible] = useState(false);
  const [visible, setVisible] = useState(false);
  const [playState, setPlayState] = useState(false);
  const [fullScrenState, setFullScrenState] = useState(false);
  const [videoDuration, setVideoDuration] = useState(0);
  const [videoCurrentTime, setVideoCurrentTime] = useState(0);

  const videoRef = useRef<any>();

  const handlePlayClick = () => {
    if (playState) {
      videoRef.current.pause();
      timer && clearTimeout(timer);
    } else {
      videoRef.current.play();
      timer = setInterval(function () {
        setVideoCurrentTime(videoRef.current.currentTime);
      }, 1000);
    }
    setPlayState(!playState);
  };

  const handleFullScrenClick = () => {
    fullScrenState
      ? videoRef.current.exitFullScreen()
      : videoRef.current.requestFullscreen();
    setFullScrenState(!fullScrenState);
  };

  const renderTime = (seconds: number) => {
    if (seconds > 3600) {
      return `${(seconds / 3600).toFixed(0)}:${((seconds % 3600) / 60).toFixed(
        0
      )}:${(seconds % 60).toFixed(0)}`;
    } else {
      return `${(seconds / 60).toFixed(0)}:${(seconds % 60).toFixed(0)}`;
    }
  };

  return (
    <div className={styles.videoPlayer}>
      <div
        className={styles.controls}
        style={{
          width,
          background: controlsVisible
            ? "rgb(255, 255, 255, 0.3)"
            : "transparent",
        }}
        onMouseOver={() => setControlsVisible(true)}
        onMouseLeave={() => setControlsVisible(false)}
      >
        <div className={styles.up}>
          <span className={styles.left}>
            {playState ? (
              <PauseOutlined onClick={handlePlayClick} />
            ) : (
              <CaretRightOutlined onClick={handlePlayClick} />
            )}
            <span>
              <span>{renderTime(videoCurrentTime)}</span> /{" "}
              <span>{renderTime(videoDuration)}</span>
            </span>
          </span>
          <span className={styles.right}>
            {fullScrenState ? (
              <CompressOutlined onClick={handleFullScrenClick} />
            ) : (
              <ExpandOutlined onClick={handleFullScrenClick} />
            )}
          </span>
        </div>
        <div className={styles.down}>
          <Progress percent={50} showInfo={false} />
        </div>
      </div>
      <video
        ref={videoRef}
        controls
        src={urls[0]}
        style={{ width }}
        onLoadedMetadata={() => setVideoDuration(videoRef.current.duration)}
      />
    </div>
  );
};

export default VideoPlayer;
